<template>
  <el-card style="margin:20px;height: 70px;">
    <el-form :inline="true">
      <el-form-item>
<!--        搜索框-->
        <el-select v-model="searchFrom.id"
                   filterable
                   clearable
                   style="width:240px;"
                   placeholder="请输入资产名称">
          <el-option
              v-for="item in tableData"
              :label="item.assetName"
              :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="primary" @click="select">搜索</el-button>
      </el-form-item>
    </el-form>
  </el-card>

<!--  展示列表-->
  <el-card style="margin:20px;">
    <div style="margin:10px 0 40px 10px;">
      <el-button type="success" style="float: right;margin-top:-3px;"
                 @click="addAsset">增加资产</el-button>
    </div>
    <el-table :data="paginatedData"
              style="height: 465px">>
      <el-table-column prop="assetName" label="资产名称" width="80" align="center"/>
      <el-table-column prop="category" label="资产类型" align="center"/>
      <el-table-column prop="modelNumber" label="型号编号" align="center"/>
      <el-table-column prop="serialNumber" label="序列号" align="center"/>
      <el-table-column prop="status" label="当前状态" align="center"/>
      <el-table-column prop="notes" label="备注" align="center"/>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button link type="danger"
                     @click="deleteRoomAsset(scope.row.id)">删除
          </el-button>

        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="tableData.length"
        @current-change="handlePageChange"
        style="margin-top:20px;margin-left:  35%"
    />

  </el-card>

<!--  新增弹框-->
  <el-dialog title="添加资产"
             v-model="addAssetVisible"
             style="width:800px;height: 500px;padding:30px;">

    <el-row :gutter="10">
      <el-col :span="12">
        <el-form label-width="120px" :inline="true">
          <el-form-item label="请选择资产" style="width: 100%;">
            <el-select v-model="searchAsset.id"
                       filterable
                       remote
                       clearable
                       placeholder="请输入要选择的资产">
              <el-option
                  v-for="item in assetSearchData"
                  :key="item.value"
                  :label="item.assetName"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="12">
        <el-button type="primary" @click="assetSearch">搜索</el-button>
        <el-button @click="resetAssetSearch">重置</el-button>
        <el-button type="danger" @click="handleClose"
                   style="float: right">取消
        </el-button>
      </el-col>
    </el-row>

    <el-row :gutter="10">
      <el-col :span="14">
        <el-table
            :data="assetSearchData"
            style="width: 500px;margin-top: 10px;height: 300px;">
          <el-table-column prop="assetName" label="资产名称"/>
          <el-table-column prop="category" label="资产类型" align="center"/>
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button type="primary" link
                         @click="toggleSelection(scope.row)">
                <span v-if="isSelected(scope.row.id)"><el-icon size="22px" color="red"><RemoveFilled/></el-icon></span>
                <span v-else><el-icon size="22px"><CirclePlusFilled/></el-icon></span>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="8">
        <p>添加的资产：</p>
        <el-scrollbar height="280px">
          <ul>
            <li v-for="item in selectedAssetValue" >
              {{ item.assetName }}
            </li>
          </ul>
        </el-scrollbar>
      </el-col>
      <el-col :span="2">
        <el-button type="primary" style="margin: 300px 0 0 10px"
                   @click="saveAsset">添加
        </el-button>
      </el-col>
    </el-row>


  </el-dialog>
</template>

<script setup>

import router from "@/router";
import {computed, nextTick, onMounted, ref} from "vue";
import qs from "qs";
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";


const tableData = ref([]);
const currentPage = ref(1);// 默认显示页码
const pageSize = ref(10); // 每页显示几条

// 计算当前页面的数据
const paginatedData = computed(() => {
  const offset = (currentPage.value - 1) * pageSize.value;
  return tableData.value.slice(offset, offset + pageSize.value);
});

// 分页变化时触发
const handlePageChange = (newPage) => {
  currentPage.value = newPage;
};
const searchFrom = ref({
  id: ''
})
let roomId = new URLSearchParams(window.location.search).get('id');
const select = () => {
  searchFrom.value.roomtId = roomId;
  let data = qs.stringify(searchFrom.value);
  axios.get(BASE_URL + '/v1/roomHave/select?' + data)
      .then((response) => {
        if (response.data.code === 2000) {
          tableData.value = response.data.data;

        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      })
}
onMounted(() => {
  select();
})
const resetSearch = () => {
  searchFrom.value.id = ''
  select();
}
const addAssetVisible = ref(false);

const addAsset = () => {
  addAssetVisible.value = true;
  assetSearch();
}
const searchAsset = ref({
  id: '',
  roomId: roomId,
})

const assetSearchData = ref({});

const assetSearch = () => {
  let data = qs.stringify(searchAsset.value);
  axios.get(BASE_URL + '/v1/fixed/select/home?' + data)
      .then((response) => {
        if (response.data.code === 2000) {
          assetSearchData.value = response.data.data;
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
          })
        }
      })
}
onMounted(() => {
  assetSearch();
})

const resetAssetSearch = () => {
  searchAsset.value.id = '';
  assetSearch();
};

const deleteRoomAsset = (id) => {
  ElMessageBox.confirm('您确定要删除吗', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    axios.delete(BASE_URL + '/v1/roomHave/delete/' + id)
        .then((response) => {
          if (response.data.code === 2000) {
            OKInfo('删除成功!');
            select();
          } else {
            ElMessage({
              message: response.data.msg,
              type: 'error',
              showClose: true,
              center: true,
            })
          }
        })
  }).catch(() => {
    Info('已取消删除')
  });
}

const allAsset = ref([]);
const selectAllAsset = () => {
  axios.get(BASE_URL + '/v1/fixed/select')
      .then((response) => {
        if (response.data.code === 2000) {
          allAsset.value = response.data.data;
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      })
}

onMounted(() => {
  selectAllAsset();
})
const selectedAssetValue = ref([]); // 已有的定义

const isSelected = (id) => {
  return selectedAssetValue.value.some(asset => asset.id === id);
};

const toggleSelection = (row) => {
  const index = selectedAssetValue.value.findIndex(asset => asset.id === row.id);

  if (index > -1) { // 如果找到，则表示该行已被选择，执行删除操作
    selectedAssetValue.value.splice(index, 1);
  } else { // 否则，执行添加操作
    selectedAssetValue.value.push({id: row.id, assetName: row.assetName});
  }
};

const handleClose = () => {
  ElMessageBox.confirm('您确定要取消吗', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    Info('已取消保存');
    selectedAssetValue.value = [];
    addAssetVisible.value = false;
  }).catch(() => {
    //取消没有操作
  });
}


const saveAssetParam = ref({
  roomId: roomId,
})
const saveAsset = () => {
  saveAssetParam.value.assetId = selectedAssetValue.value.map(asset => asset.id).join(',');
  let data = qs.stringify(saveAssetParam.value);
  axios.post(BASE_URL + '/v1/roomHave/save', data)
      .then((response) => {
        if (response.data.code === 2000) {
          OKInfo('保存成功!');
          selectedAssetValue.value = [];
          addAssetVisible.value = false;
          select();
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      })
}
</script>


<style scoped>
.checkbox-item {
  display: block;
  margin: 10px 0;
}

/* 定义进入和离开的动画 */
.fade-enter-active, .fade-leave-active {
  transition: opacity .5s ease, transform .5s ease;
}

.fade-enter-from, .fade-leave-to /* .fade-leave-active in <2.1.8 */
{
  opacity: 0;
  transform: scale(0);
}

.fade-enter-to, .fade-leave-from {
  opacity: 1;
  transform: scale(1);
}
</style>